package org.mobilesynergies.android.epic.service.core;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpParams;
import org.mobilesynergies.android.epic.service.R;
import org.mobilesynergies.android.epic.service.administration.ServiceAdministrationActivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Allows the user to start several activities. E.g., configuration, registration, etc. 
 *   
 * @author Peter
 */

public class MenuActivity extends ServiceAdministrationActivity{


	private static final String REGISTRATIONSERVICE_HOSTNAME = "http://blindeshendl.cg.tuwien.ac.at";
	private static final String REGISTRATIONSERVICE_PATHNAME = "/epic/users/";

	/** 
	 * Called when the activity is first created. 
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.menu);
		if(Preferences.isRegistered(this)){

		} else {
			registerNewUser();
		}

		updateUI();
	}

	Handler handlerSendEmail = new Handler(){
		public void handleMessage(Message msg) {
			final String link = Preferences.getUserUrl(MenuActivity.this);
			if(link==null){
				Toast.makeText(MenuActivity.this, "not registered yet", Toast.LENGTH_SHORT);
			}
			new AlertDialog.Builder(MenuActivity.this)
			.setTitle("Send Link")
			.setMessage("With the Epic service you can send commands from your PC to your phone.").setNeutralButton("Send me the link!", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					Intent i = new Intent(Intent.ACTION_SEND);
					i.setType("message/rfc822");
					//Bundle b = new Bundle();
					i.putExtra(Intent.EXTRA_SUBJECT, "The link to your Epic page");
					i.putExtra(Intent.EXTRA_TEXT, "Open the browser on your PC and go to: "+ link +"\nYour phone must also be connected to the Epic network. \nHave fun!");
					startActivity(Intent.createChooser(i, "Send Link"));  
				}
			})
			.show();
		}				

	};

	Handler handlerUpdateUi = new Handler(){
		public void handleMessage(android.os.Message msg) {
			updateUI();			
		};
	};


	private void updateUI() {
		boolean bServiceConnected = false;
		if(mEpicService!=null) {
			bServiceConnected = mEpicService.isConnectedToEpicNetwork();
		}
		
		boolean isregistered = Preferences.isRegistered(this);
		Button send = (Button) findViewById(R.id.menu_button_sendlink);
		Button delete = (Button) findViewById(R.id.menu_button_delete);
		Button register = (Button) findViewById(R.id.menu_button_register);
		TextView status = (TextView) findViewById(R.id.menu_text_registrationstatus);

		String statusString = ""; 
			
		if(isregistered){
			String user = Preferences.getUserName(this);
			String location = Preferences.getUserUrl(this);
			statusString = "registered as user \n"+user+" at location \n"+location;
			
			
			register.setEnabled(false);

			send.setEnabled(true);
			send.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					handlerSendEmail.sendEmptyMessage(0);					
				}
			});


			delete.setEnabled(true);
			delete.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					deleteUser();					
				}
			});
		} else {
			statusString = "not registered yet";
			send.setEnabled(false);
			delete.setEnabled(false);
			register.setEnabled(true);
			register.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					registerNewUser();
				}
			});
		}
		
		if(bServiceConnected){
			statusString+="\nconnected to epic network";
		} else {
			statusString+="\nnot connected to epic network";
		}
		
		status.setText(statusString);
		
		
		
		
		
	}


	protected void deleteUser() {
		Thread deleteThread = new Thread(){
			@Override
			public void run() {

				if(! Preferences.isRegistered(MenuActivity.this)){
					return; 				
				}

				String url = Preferences.getUserUrl(MenuActivity.this);

				HttpClient httpClient = new DefaultHttpClient();
				HttpParams params = httpClient.getParams(); 
				HttpClientParams.setRedirecting(params, false);

				HttpDelete deleteRequest = new HttpDelete(url);
				//send http delete
				HttpResponse httpResponse = null;
				try {
					httpResponse = httpClient.execute(deleteRequest);
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}

				if(httpResponse == null){
					//TODO error handling
					return;
				}



				//delete username, password, and location from settings file
				Preferences.deleteUserName(MenuActivity.this);
				Preferences.deleteUserPassword(MenuActivity.this);
				Preferences.deleteUserUrl(MenuActivity.this);



				//update ui
				handlerUpdateUi.sendEmptyMessage(0);
			}
		};
		deleteThread.start();

	}


	protected void registerNewUser() {
		Thread registerThread = new Thread(){
			@Override
			public void run() {

				HttpClient httpClient = new DefaultHttpClient();
				HttpParams params = httpClient.getParams(); 
				HttpClientParams.setRedirecting(params, false);

				HttpPost postRequest = new HttpPost(REGISTRATIONSERVICE_HOSTNAME+REGISTRATIONSERVICE_PATHNAME);
				//TODO auto create random username and do url encoding
				String username = "epic00"+randomString(10);

				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
				nameValuePairs.add(new BasicNameValuePair("user[name]", username));
				nameValuePairs.add(new BasicNameValuePair("commit", "Create+User"));
				try {
					postRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				} catch (UnsupportedEncodingException e1) {
					e1.printStackTrace();
				}

				//send http post
				HttpResponse httpResponse = null;
				try {
					httpResponse = httpClient.execute(postRequest);
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}

				if(httpResponse == null){
					//TODO error handling
					return;
				}



				int statuscode = httpResponse.getStatusLine().getStatusCode();
				HttpEntity entity = httpResponse.getEntity();

				try {
					InputStream s = entity.getContent();
					if (s != null) {
						StringBuilder sb = new StringBuilder();
						String line;

						try {
							BufferedReader reader = new BufferedReader(new InputStreamReader(s, "UTF-8"));
							while ((line = reader.readLine()) != null) {
								sb.append(line).append("\n");
							}
						} finally {
							s.close();
						}
						String html = sb.toString();
						Log.d("LALA",html);

					} 
				} catch (IllegalStateException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}


				String location = null;

				//TODO if(statuscode==302){
				if(httpResponse.containsHeader("Location")){
					Header locationHeader = httpResponse.getFirstHeader("Location");
					location = locationHeader.getValue();
				} 

				if(location==null){
					//TODO 
				} else {
					//TODO extract username and password from location
					String password = username;

					//put username, password, and location in settings file
					Preferences.setUserName(MenuActivity.this, username);
					Preferences.setUserPassword(MenuActivity.this, password);
					Preferences.setUserUrl(MenuActivity.this, location);
				}

				//TODO } else {
				//http request was unsuccessful -> display reason to user
				//}

				//update ui
				handlerUpdateUi.sendEmptyMessage(0);
			}

			private String randomString(int length) {
				String string = "";
				for (int i = 0; i < length; i++) {
					double randomNumber = Math.random();
					int randomNumberSetup = (int)(randomNumber * 26.0)  + 'a';
					char randomCharacter = (char) randomNumberSetup;
					string+=randomCharacter;
				}
				return string;
			}
		};
		registerThread.start();
	}


	@Override
	protected void onConnected() {
		updateUI();		
	}


	@Override
	protected void onConnectedToEpicNetwork() {
		updateUI();
	}


	@Override
	protected void onDisconnected() {
		updateUI();
	}



}